<template>
    <div class="condition-item">
        <div class="item-label">{{field.label}}：</div>
        <div class="item-value-box">
            <!--文本-->
            <template v-if="['text','number'].includes(field.type)">
                <input class="value-ipt" :type="field.type" placeholder="请输入" v-model="iptValue" @change="onInput" @keydown.enter="onKeydown">
            </template>

            <!--单选、多选-->
            <template v-if="['picklist','multiple'].includes(field.type)">
                <el-scrollbar>
                    <div class="options-box">
                            <div class="option-item" :class="{active: selectValue.indexOf(item.id || item.name) > -1}" v-for="item in field.options" @click="onSelect(item.id || item.name)">{{item.name}}</div>
                    </div>
                </el-scrollbar>
            </template>

            <!--日期时间-->
            <template v-if="['date','datetime','daterange','datetimerange','month'].includes(field.type)">
                <!--<el-date-picker
                        v-model="iptValue"
                        type="datetime"
                        placeholder="请选择"
                />-->
                <m-datepicker
                        :value="iptValue"
                        :type="field.type"
                        :value-format="field.length || 'YYYY-MM-DD HH:mm'"
                        placeholder="请选择"
                        :rewriteInput="true"
                        @change="onDate"
                ></m-datepicker>
            </template>

            <!--引用类型-->
            <template v-if="field.type === 'reference'">

                <m-reference
                        :value="iptValue"
                        :entity-key="field.entityKey"
                        :value-key="field.valueKey"
                        @change="onReference"
                        :placeholder="field.placeholder || '请选择'"
                        :cols="field.refCols"
                        :url="field.refUrl"
                        :param="field.refParam"
                        :rewriteInput="field.rewriteInput"
                        :searchField="field.searchField"
                ></m-reference>
            </template>

            <!--选择-->
            <template v-if="field.type === 'select'">
                <m-select
                        :options="field.options"
                ></m-select>
            </template>
        </div>
    </div>
</template>

<script setup>
  import MDatepicker from '@/components/common/Datepicker/Datepicker'
  import MReference from '@/components/common/Reference/Reference'
  import MSelect from '@/components/common/Select/Select'
  import { ref , defineProps,watch,defineEmits} from 'vue'

    const props = defineProps({
      field: {
        default: {}
      },
      isReset: {
        default: false
      },
      value: {}
    });
    const emit = defineEmits(['update:isReset','m-change'])

    let selectValue = ref([]),
      iptValue = ref('');

    /*watch(iptValue,(val)=>{
      console.log(val);
    });*/

    watch(() => props.isReset,(val)=>{
      reset();
      // if (val) reset();
    })

    watch(() => props.value, (val) =>{
      // console.log('默认条件conditionItem',val);
      let {type,field_id} = props.field,
        query = val && val[field_id];
      if (['multiple'].includes(type)){
        selectValue.value = query && query.split(',') || []
      }else if (['picklist'].includes(type)) {
        selectValue.value = query && [query] || []
      }/*else if (type === 'reference'){
        let {entityKey,valueKey} = props.field;
      }*/
      else if (['daterange','datetimerange'].includes(type)) {
        let value = [];
        if (typeof field_id === 'object' && val){
          field_id.forEach(item =>{
            value.push(val[item]);
          });
        }
        iptValue.value = value;
      }
      else{
        iptValue.value = query || '';
      }
    },{immediate: true})

  function onInput() {
    handleChange(iptValue.value);
  }
  //230901 yan 增加输入框 回车键 触发搜索
  function onKeydown() {
    handleChange(iptValue.value || '',true);
  }
  //230901 end
  function onDate(val) {
    // console.log('onDate',val);
    iptValue.value = val;
    handleChange(val);
  }
  function onSelect(val) {
    let arr = selectValue.value,
      index = arr.indexOf(val),
      type = props.field.type,
      auto = false;
    //单选
    if (type === 'picklist'){
      if (index > -1) arr = [];
      else arr = [val];
      auto = true;
    }
    //多选
    else {
      if (index > -1) arr.splice(index,1);
      else arr.push(val);
    }

    selectValue.value = arr;

    handleChange(arr.join(','),auto);
  }
  function onReference(data) {
    let {field_id,show_field,entityKey,valueKey,type} = props.field;
    let value = '';
    if (valueKey){
      value = {};
      valueKey.forEach(item => {
        if (typeof item === 'string') value[item] = data[item] || '';
        if (typeof item === 'object') {
          let key = Object.keys(item)[0],
            val = item[key];
          value[key] = data[val] || '';
        }
      })
    }else {
      value = data[field_id]
    }
    handleChange(value);
  }

  //230901 yan 触发字段修改，val搜索参数值，auto {Boolean}自动触发
  function handleChange(val,auto) {
    let obj = {
      field: props.field,
      value: val,
      auto
    }
    emit('m-change',obj);
  }
  //重置
  function reset() {
    selectValue.value = [];
    iptValue.value = '';
    if (['daterange','datetimerange'].includes(props.field.type)) {
      iptValue.value = [];
    }
    // emit('update:isReset',false)
  }
</script>

<style scoped lang="less">
.condition-item{
    width: 100%;
    display: flex;
    color: #666666;
    font-size: 14px;
    .item-label{
        height: 40px;
        background: #F8F8F8;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        width: 100px;
        justify-content: flex-end;
    }
    .item-value-box{
        flex: 1;
        width: 0;
        overflow: hidden;
        padding: 0 10px;

        .options-box{
            height: 40px;
            display: flex;
            align-items: center;
            width: auto;
            .option-item{
                padding: 5px 7px;
                margin: 0 13px;
                cursor: pointer;
                flex-shrink: 0;
                &:hover{
                    background: #f3f3f3;
                }
                &.active{
                    background: #E9F0FF;
                    color: #2D6FF7;
                }
            }
        }
        ::v-deep{
            .date-ipt{
                &:hover{
                    background: #f3f3f3;

                }
            }
        }
        .value-ipt{
            height: 40px;
            width: 100%;
            &:hover{
                background: #f3f3f3;

            }
        }
    }
}
</style>
